import React from "react"
import {Table,Button,Spin,message,Modal,Menu,Dropdown,Upload} from 'antd';
import {getFileListByPage,delFile,getViewUrlDbPath,uploadFileUrl} from "../api/index"
import MyPagination from "../components/pagination"
import {PlusOutlined,CloudUploadOutlined} from "@ant-design/icons";
import {fileSuffixStr} from '../utils/common-data'
import MyProgress from "../components/progress";
import {checkFile} from "../confun/index"

export default class DbFilePage extends React.Component{
    constructor(props){
        super(props);

        this.editFunc = this.editFunc.bind(this);
        this.delFunc = this.delFunc.bind(this);

        this.state = {
            pageR:{
                page:1,
                size:10
            },
            total:1,
            columnData:{},
            loading: true,
            url:'',
            token:'',
            columns: [
                {
                    title: "序号",
                    width: 80,
                    align: "center",
                    dataIndex:"myIndex",
                    key:"myIndex"
                },
                {
                    title: "文件名",
                    dataIndex: "name",
                    key:"myIndex",
                    minWidth: 150,
                    align: "center"
                },
                {
                    title: "版本号",
                    dataIndex: "version",
                    key:"version",
                    minWidth: 60,
                    align: "center"
                },
                {
                    title: "文件大小M",
                    dataIndex: "mySize",
                    key:"mySize",
                    align: "center"
                },
                {
                    title: "创建者",
                    dataIndex: "creator",
                    key:"creator",
                    align: "center"
                },
                {
                    title: "创建时间",
                    dataIndex: "createTime",
                    key:"createTime",
                    align: "center"
                },
                {
                    title: "修改者",
                    dataIndex: "modifier",
                    key:"modifier",
                    align: "center"
                },
                {
                    title: "修改时间",
                    dataIndex: "modifyTime",
                    key:"modifyTime",
                    align: "center"
                },
                {
                    title: "操作",
                    align: "center",
                    key:"edit",
                    render: (r)=> {
                        return (
                            <span>
                                <Button
                                    className={'d-btClass'}
                                    size="small"
                                    type="info"
                                    shape="round"
                                    onClick={()=>this.editFunc(r)}
                                >
                                    编辑/预览
                                </Button>
                            <Button
                                className={'d-btClass'}
                                size="small"
                                type="danger"
                                shape="round"
                                ghost={true}
                                onClick={()=>this.delFunc(r)}
                            >
                                删除
                            </Button>
                            </span>
                        )
                    }
                }
            ],
            ListData: [],
            fileName: '',
            percent: 0,
            visible: false
        };
    }

    render() {
        return <div id={'dbFile'}>
            <Spin spinning={this.state.loading}>
                <Table
                    size="small"
                    style={{width: '100%'}}
                    columns={this.state.columns}
                    pagination={false}
                    dataSource={this.state.ListData}
                />
            </Spin>
            <MyPagination
                size={this.state.pageR.size}
                page={this.state.pageR.page}
                total={this.state.total}
                pageChange={this.pageChange}
            />
            <Upload
                className={'up-cr-bt'}
                name={'file'}
                action={uploadFileUrl}
                showUploadList={false}
                accept={fileSuffixStr}
                beforeUpload={this.beforeUpload.bind(this)}
                onChange={this.onChange.bind(this)}
            >
                <Button
                    className={'up_'}
                    size="small"
                    type="info"
                >
                    上传<CloudUploadOutlined />
                </Button>
            </Upload>
            <Dropdown overlay={
                <Menu onClick={this.handleMenuClick}>
                    <Menu.Item key="word">
                        <svg className="icon" aria-hidden="true">
                            <use xlinkHref="#icon-word1"/>
                        </svg>
                        <span style={{textAlign: "center"}}>文字文档</span>
                    </Menu.Item>
                    <Menu.Item key="excel">
                        <svg className="icon" aria-hidden="true">
                            <use xlinkHref="#icon-excel1"/>
                        </svg>
                        <span style={{textAlign: "center"}}>表格文档</span>
                    </Menu.Item>
                    <Menu.Item key="ppt">
                        <svg className="icon" aria-hidden="true">
                            <use xlinkHref="#icon-ppt4"/>
                        </svg>
                        <span style={{textAlign: "center"}}>演示文档</span>
                    </Menu.Item>
                </Menu>
            } trigger={['click']}>
                <Button
                    className={'up-cr-bt'}
                    size="small"
                    type="info"
                >
                    新建<PlusOutlined />
                </Button>
            </Dropdown>
            <MyProgress
                fileName={this.state.fileName}
                percent={this.state.percent}
                visible={this.state.visible}
            />
        </div>
    }

    componentDidMount() {
        this.getFileListByPage(this.state.pageR);
        document.addEventListener("visibilitychange",this.handleVisible);
    }

    componentWillUnmount() {
        document.removeEventListener("visibilitychange",this.handleVisible)
    }

    handleVisible = (e)=>{
        if (e.target.visibilityState === 'visible' || e.target.visibilityState === 'unloaded'){
            this.getFileListByPage(this.state.pageR);
        }
    };

    beforeUpload = (file) =>{
        return checkFile(file);
    };

    onChange = (info) => {
        if (info.event){
            if (info.file.status === 'uploading'){
                this.setState({
                    fileName: info.file.name,
                    percent: info.file.percent,
                    visible: true
                })
            }
        }
        if (info.file.status === 'done') {
            this.setState({
                visible: false
            });
            message.success(`${info.file.name} 上传成功`);
            this.getFileListByPage(this.state.pageR)
        } else if (info.file.status === 'error') {
            this.setState({
                visible: false
            });
            message.error(`${info.file.name} 上传失败`);
        }
    };

    editFunc = (r)=>{
        this.getViewPath(r);
    };

    delFunc = (r)=>{
        Modal.confirm({
            title: '提示',
            content: '此操作将永久删除该文件, 是否继续?',
            okType:'danger',
            okText: '确认',
            style:{marginTop: '5%'},
            cancelText: '取消',
            confirmLoading:true,
            maskClosable:true,
            onOk:()=>{this.delFile(r.id)}
        });
    };

    handleMenuClick = (e) => {
        this.createFile(e.key);
    };

    getFileListByPage = (p)=>{
        this.openLoading();
        getFileListByPage(p).then((res)=>{
            const rList = res.data.data.content;
            // 重新定义index序号 以及文件大小，-- 也可以用函数实现 -- react中没有类似vue管道过滤器
            for (let i=0;i<rList.length;i++) {
                rList[i].key = rList[i].myIndex = (i + 1 + (p.page - 1) * p.size);
                rList[i].mySize = (Number(rList[i].size) / (1024 * 1024)).toFixed(3)
            }
            this.setState({
                ListData: rList,
                total: res.data.data.totalElements
            });
            this.cleanLoading()
        }).catch(()=>{
            this.cleanLoading();
            message.error("请求异常");
        })
    };

    delFile = (id)=>{
        this.openLoading();
        delFile({id}).then((res)=>{
            if (res.data.data){
                message.success(res.data.msg);
                this.getFileListByPage(this.state.pageR);
            }else {
                message.error(res.data.msg);
            }
            this.cleanLoading();
        }).catch(()=>{
            this.cleanLoading();
            message.error("请求异常");
        })
    };

    getViewPath = (r)=>{
        const p = {
            fileId: r.id,
            userId: r.userId
        };
        this.openLoading();
        getViewUrlDbPath(p).then((res)=>{
            this.cleanLoading();
            const r = res.data.data;
            sessionStorage.wpsUrl = r.wpsUrl;
            sessionStorage.token = r.token;
            // 开启了hash模式，注意这里的 #，生不如死
            this.jumpTo('#/viewFile')
        }).catch(()=>{
            this.cleanLoading();
            message.error("请求异常");
        });
    };

    createFile = (val) =>{
        sessionStorage.createFileType = val;
        // 开启了hash模式，注意这里的 #，生不如死
        this.jumpTo('#/createFile')
    };

    jumpTo = (url)=>{
        window.open(url,'_blank');
    };

    pageChange = (par) => {
        // setState是异步请求，通过传参处理
        this.getFileListByPage(par);
        this.setState({
            pageR:{
                page:par.page,
                size:par.size
            }
        });
    };

    openLoading = ()=>{
        this.setState({
            loading: true
        });
    };

    cleanLoading = ()=>{
        this.setState({
            loading: false
        });
    };

}
